package cn.qyd.aqs;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 邱运铎
 * @date 2024-03-20 10:07
 */
public class ReentrantReadWriteCachedDataDemo {
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private Object data;
    private boolean checkValid;

    public void processCachedData() {
        lock.readLock().lock();

        if (!checkValid) {
            lock.readLock().unlock();
            lock.writeLock().lock();
            try {
                if (!checkValid) {
                    data = fetchDataFromDatabase();
                    checkValid = true;
                    System.out.println(Thread.currentThread().getName() + " 正在从数据库拉取数据中。。。");
                }
                lock.readLock().lock();
            } finally {
                lock.writeLock().unlock();
            }
        }

        try {
            use();
        } finally {
            lock.readLock().unlock();
        }
    }

    private Object fetchDataFromDatabase() {
        return new Object();
    }

    private void use() {
        System.out.println("Data : " + data + "  正在被线程" +Thread.currentThread().getName() +  "使用" );
    }

    public static void main(String[] args) {
        ReentrantReadWriteCachedDataDemo demo = new ReentrantReadWriteCachedDataDemo();
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> demo.processCachedData(),"Thread " + i).start();
        }
    }
}
